package com.magic.sms.listener;
import com.magic.sms.config.SmsProperties;
import com.magic.sms.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author lan.jianyuan
 * @create 2021-01-30-16:30
 */
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsListener {
    
    @Autowired
    private SmsUtils smsUtils;
    
    @Autowired
    private SmsProperties prop;
    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "magic.sms.queue", durable = "true"),
            exchange = @Exchange(value = "magic.sms.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
            key = {"sms.verify.code"}))
    public void listenSms(Map<String, String> msg) throws Exception {
        if (msg == null || msg.size() <= 0) {
            // 放弃处理
            return;
        }
        String phone = msg.get("phone");
        String code = msg.get("code");
        
        if (StringUtils.isNoneBlank(phone) && StringUtils.isNoneBlank(code)) {
            // 发送消息
            this.smsUtils.sendSms(phone, code,
                    prop.getSignName(),
                    prop.getVerifyCodeTemplate());
        }
    }
}
